<template>
  <div class="app-container">
    <el-container>
      <el-aside width="400px">
        <box-card :key="infoLoad" style="margin-top: 0.5rem" />
        <el-card style="margin-top: 2rem;">
          <pie-chart />
        </el-card>
      </el-aside>
      <el-main style="padding: 0;margin-left: 2rem">
        <el-tabs v-model="activeName1" @tab-click="personInfo">
          <el-tab-pane label="活动" name="active">
            <span slot="label"><i class="el-icon-message-solid" /> 活动</span>
            <el-card>
              <div v-if="range.length>0">
                <div v-for="item in range" :key="item.solutionId">
                  <panel-group :item-data="item" />
                  <el-divider />
                </div>
              </div>
              <div v-else style="text-align: center">暂时没有内容哦...</div>
              <el-pagination
                style="margin-top: 20px;"
                background
                :current-page="currentPage"
                :page-sizes="[10, 25, 50, 100]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalNum"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-card>
          </el-tab-pane>
          <el-tab-pane label="设置" name="setting" :disabled="enableSet()">
            <span slot="label"><i class="el-icon-setting" /> 设置</span>
            <el-card>
              <el-tabs v-model="activeName2" tab-position="left">
                <el-tab-pane label="基本信息" name="info">
                  <el-form ref="infoForm" :model="infoForm" label-width="80px" :rules="rules">
                    <el-form-item label="昵称" prop="nickName">
                      <el-input v-model="infoForm.nickName" />
                    </el-form-item>
                    <el-form-item label="性别" prop="sex">
                      <el-select v-model="infoForm.sex" placeholder="请选择性别">
                        <el-option label="未知" value="0" />
                        <el-option label="男" value="1" />
                        <el-option label="女" value="2" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="加入时间">
                      <el-input :value="infoForm.regTime" disabled />
                    </el-form-item>
                    <el-form-item label="个性签名">
                      <el-input
                        v-model="infoForm.description"
                        type="textarea"
                        placeholder="请输入签名哦"
                        show-word-limit
                        maxlength="100"
                        :竞赛size="{ minRows: 5, maxRows: 5}"
                      />
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" :loading="infoLoad" @click="submitInfo">保存</el-button>
                    </el-form-item>
                  </el-form>
                </el-tab-pane>
                <el-tab-pane label="我的头像" name="avatar">
                  <el-row>
                    <el-col :span="11">
                      <el-upload
                        ref="upload"
                        accept=".jpg,.jpeg,.png,.gif"
                        style="float:right;"
                        :headers="headers"
                        name="image"
                        :data="imgData"
                        :action="`${host}/user/user/uploadImage`"
                        :limit="limitCount"
                        :on-success="successImg"
                        :on-error="errorImg"
                        list-type="picture-card"
                        :on-change="uploadChange"
                        :before-upload="uploadBefore"
                        :class="{hide:hideUpload}"
                        :auto-upload="false"
                      >
                        <i slot="default" class="el-icon-plus" />
                        <div slot="file" slot-scope="{file}">
                          <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                          <span class="el-upload-list__item-actions">
                            <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)"><i class="el-icon-zoom-in" /></span>
                            <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)"><i class="el-icon-delete" /></span>
                          </span>
                        </div>
                      </el-upload>
                      <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt="">
                      </el-dialog>
                    </el-col>
                    <el-col :span="2" style="text-align: center">
                      <el-divider direction="vertical" />
                    </el-col>
                    <el-col :span="11">
                      <el-avatar :size="150" :src="avatar()" alt="当前头像" @error="true">
                        <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" alt="">
                      </el-avatar>
                    </el-col>
                  </el-row>
                  <el-row>
                    <p style="text-align: center">请选择图片上传：支持JPG、PNG、GIF等格式，图片需不大于5M</p>
                  </el-row>
                  <el-row style="text-align: center">
                    <el-button type="success" :disabled="imageBtn" :loading="infoLoad" @click="uploadImage">更新</el-button>
                  </el-row>
                </el-tab-pane>
                <el-tab-pane label="学校信息" name="school">
                  <el-form ref="schoolForm" :model="schoolForm" label-width="80px" :rules="rules">
                    <el-form-item label="学校">
                      <el-input v-model="schoolForm.school" show-word-limit maxlength="30" />
                    </el-form-item>
                    <el-form-item label="班级">
                      <el-input :value="schoolForm.clbum" show-word-limit maxlength="30" />
                    </el-form-item>
                    <el-form-item label="学号">
                      <el-input v-model="schoolForm.number" show-word-limit maxlength="30" />
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" :loading="schoolLoad" @click="submitSchool">保存</el-button>
                    </el-form-item>
                  </el-form>
                </el-tab-pane>
                <el-tab-pane label="更换邮箱" name="email">
                  <el-form ref="emailForm" :model="emailForm" :rules="rules" label-width="80px">
                    <el-form-item label="账号密码" prop="password">
                      <el-input v-model="emailForm.password" placeholder="输入账号密码" type="password" />
                    </el-form-item>
                    <el-form-item label="新邮箱" prop="email">
                      <el-input v-model="emailForm.email" placeholder="输入新邮箱后获取验证码" />
                    </el-form-item>
                    <el-form-item label="验证码" prop="code">
                      <el-input v-model="emailForm.code" placeholder="输入新邮箱的验证码">
                        <el-button slot="append" class="code-hover" :loading="codeLoad" @click="sendCaptcha">获取验证码</el-button>
                      </el-input>
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" :loading="emailLoad" @click="submitEmail">立即更换</el-button>
                    </el-form-item>
                  </el-form>
                </el-tab-pane>
                <el-tab-pane label="修改密码" name="password">
                  <el-form ref="passForm" :model="passForm" :rules="rules" label-width="80px">
                    <el-form-item label="原密码" prop="password">
                      <el-input v-model="passForm.password" type="password" />
                    </el-form-item>
                    <el-form-item label="新密码" prop="newPass">
                      <el-input v-model="passForm.newPass" type="password" />
                    </el-form-item>
                    <el-form-item label="确认密码" prop="rePass">
                      <el-input v-model="passForm.rePass" type="password" />
                    </el-form-item>
                    <el-form-item label="验证码" prop="code">
                      <el-input v-model="passForm.code">
                        <el-button slot="append" class="code-hover" :loading="codeLoad" @click="sendCaptcha2">获取验证码</el-button>
                      </el-input>
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" :loading="passLoad" @click="submitPassword">立即修改</el-button>
                    </el-form-item>
                  </el-form>
                </el-tab-pane>
              </el-tabs>
            </el-card>
          </el-tab-pane>
        </el-tabs>
      </el-main>
    </el-container>
  </div>
</template>
<script>

import BoxCard from './components/BoxCard'
import PieChart from './components/PieChart'
import PanelGroup from './components/PanelGroup'
import {
  getAvatar, getEmail,
  getToken,
  getUserId,
  removeAvatar, removeEmail,
  removeRoleId,
  removeToken,
  removeUserId,
  setAvatar
} from '@/utils/auth'
import { baseInfo, personInfo, personRecord, schoolInfo, updateEmail, updatePassword, validateCode } from '@/api/user'
import { validEmail } from '@/utils/validate'
import { Message } from 'element-ui'
import { resetRouter } from '@/router'

export default {
  components: {
    BoxCard,
    PieChart,
    PanelGroup
  },
  data() {
    const validateEmail = (rule, value, callback) => {
      if (!validEmail(value)) {
        callback(new Error('请输入正确的邮箱'))
      } else {
        callback()
      }
    }
    const validatePassword2 = (rule, value, callback) => {
      if (value.length < 8) {
        callback(new Error('请输入不小于8位的密码'))
      } else if (value !== this.passForm.newPass) {
        callback(new Error('两次输入密码不相等'))
      } else {
        callback()
      }
    }
    return {
      currentPage: 1,
      pageSize: 10,
      totalNum: 0,
      hideUpload: false,
      range: [],
      activeName1: 'active',
      activeName2: 'info',
      limitCount: 1,
      headers: {
        Authorization: getToken(),
        user_id: getUserId()
      },
      imgData: { userId: getUserId() },
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      imageBtn: true,
      rules: {
        nickName: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
        sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 8, max: 50, message: '密码长度不低于8位', trigger: 'blur' }],
        newPass: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 8, max: 50, message: '密码长度不低于8位', trigger: 'blur' }],
        email: [{ required: true, trigger: 'blur', validator: validateEmail }],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { min: 6, max: 6, message: '验证码长度为6位', trigger: 'blur' }
        ],
        rePass: [{ required: true, trigger: 'blur', validator: validatePassword2 }]
      },
      infoLoad: false,
      schoolLoad: false,
      emailLoad: false,
      passLoad: false,
      codeLoad: false,
      infoForm: {
        nickName: '',
        sex: '0',
        description: '',
        regTime: ''
      },
      schoolForm: {
        school: '',
        clbum: '',
        number: ''
      },
      emailForm: {
        password: '',
        email: '',
        code: ''
      },
      passForm: {
        password: '',
        newPass: '',
        rePass: '',
        code: ''
      },
      userId: -1,
      host: process.env.VUE_APP_BASE_API
    }
  },
  watch: {
    $route: {
      handler() {
        if (this.$route.query.userId !== undefined) {
          this.userId = this.$route.query.userId
          this.personRecord()
        } else if (getUserId() !== undefined) {
          this.userId = getUserId()
          this.personRecord()
        }
      },
      deep: true
    }
  },
  mounted() {
    if (this.$route.query.userId !== undefined) {
      this.userId = this.$route.query.userId
      this.personRecord()
    } else if (getUserId() !== undefined) {
      this.userId = getUserId()
      this.personRecord()
    }
  },
  methods: {
    submitInfo() {
      this.$refs.infoForm.validate(valid => {
        if (valid) {
          this.infoLoad = true
          const formData = new FormData()
          formData.set('userId', getUserId())
          formData.set('nick', this.infoForm.nickName)
          formData.set('sex', this.infoForm.sex)
          formData.set('description', this.infoForm.description)
          baseInfo(formData).then(() => {
            this.$message.success('更新基本信息成功')
            this.infoLoad = false
          }).catch(() => { this.infoLoad = false })
        }
      })
    },
    submitSchool() {
      this.schoolLoad = true
      const formData = new FormData()
      formData.set('userId', getUserId())
      formData.set('school', this.schoolForm.school)
      formData.set('clbum', this.schoolForm.clbum)
      formData.set('number', this.schoolForm.number)
      schoolInfo(formData).then(() => {
        this.$message.success('更新学校信息成功')
        this.schoolLoad = false
      }).catch(() => { this.schoolLoad = false })
    },
    submitEmail() {
      this.$refs.emailForm.validate(valid => {
        if (valid) {
          this.emailLoad = true
          const formData = new FormData()
          formData.set('userId', getUserId())
          formData.set('password', this.emailForm.password)
          formData.set('email', this.emailForm.email)
          formData.set('code', this.emailForm.code)
          updateEmail(formData).then(res => {
            this.$message.success(res.message)
            this.emailLoad = false
            this.logout()
          }).catch(() => {
            this.emailLoad = false
          })
        }
      })
    },
    submitPassword() {
      this.$refs.passForm.validate(valid => {
        if (valid) {
          this.passLoad = true
          const formData = new FormData()
          formData.set('userId', getUserId())
          formData.set('password', this.passForm.password)
          formData.set('newPass', this.passForm.newPass)
          formData.set('rePass', this.passForm.rePass)
          formData.set('email', getEmail())
          formData.set('code', this.passForm.code)
          updatePassword(formData).then(res => {
            this.$message.success(res.message)
            this.passLoad = false
            this.logout()
          }).catch(() => {
            this.passLoad = false
          })
        }
      })
    },
    logout() {
      removeToken()
      removeUserId()
      removeAvatar()
      removeRoleId()
      removeEmail()
      resetRouter()
      setTimeout(() => {
        this.$router.push('/login?redirect=profile')
      }, 1000)
    },
    sendCaptcha() {
      this.codeLoad = true
      if (!validEmail(this.emailForm.email)) {
        Message.error('邮箱输入错误！')
        return
      }
      const formData = new FormData()
      formData.append('to', this.emailForm.email)
      validateCode(formData).then(res => {
        this.codeLoad = false
        Message.success(res.message)
      }).catch(() => {
        this.codeLoad = false
      })
    },
    sendCaptcha2() {
      this.codeLoad = true
      const formData = new FormData()
      formData.append('to', getEmail())
      validateCode(formData).then(res => {
        Message.success(res.message)
        this.codeLoad = false
      }).catch(() => {
        this.codeLoad = false
      })
    },
    personInfo(targetName) {
      if (targetName.paneName === 'setting') {
        personInfo({ userId: getUserId() }).then(res => {
          this.infoForm.sex = String(res.data.sex)
          this.infoForm.description = res.data.description
          this.infoForm.nickName = res.data.nick
          this.infoForm.regTime = res.data.regTime
          this.schoolForm.school = res.data.school
          this.schoolForm.clbum = res.data.clbum
          this.schoolForm.number = res.data.number
        })
      }
    },
    personRecord() {
      personRecord({ userId: this.userId, current: this.currentPage, size: this.pageSize }).then(res => {
        this.range = res.data.records
        this.totalNum = parseInt(res.data.total)
      })
    },
    imageChange() {
      this.hideUpload = this.$refs.upload.uploadFiles.length >= this.limitCount
      this.imageBtn = this.$refs.upload.uploadFiles.length < this.limitCount
    },
    uploadChange(file, fileList) {
      this.imageChange()
    },
    uploadBefore(file) {
      if (file.size > 5242880) {
        this.$message.warning('图片上限为5M')
        this.$refs.upload.uploadFiles = []
        this.imageChange()
        return false
      } else if (file.type !== 'image/jpeg' && file.type !== 'image/gif' && file.type !== 'image/jpg' && file.type !== 'image/png') {
        this.$refs.upload.uploadFiles = []
        this.$message.warning('文件类型限制为jpg,jpeg,gif,png')
        this.imageChange()
        return false
      } else {
        this.infoLoad = true
        return true
      }
    },
    uploadImage() {
      this.$refs.upload.submit()
    },
    successImg(response, file, fileList) {
      this.infoLoad = false
      if (response.code === '00000') {
        this.$message({ message: response.message, type: 'success' })
        setAvatar(response.data, 864000)
        this.$router.go(0)
      } else {
        this.$message({ message: response.message, type: 'error' })
      }
      this.$refs.upload.uploadFiles = []
      this.imageChange()
    },
    errorImg(response, file, fileList) {
      this.hideUpload = false
      this.imageBtn = true
      this.$message({ message: response.message, type: 'error' })
      this.$refs.upload.uploadFiles = []
      this.imageChange()
    },
    handleRemove(file) {
      this.$refs.upload.uploadFiles = []
      this.imageChange()
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleSizeChange(size) {
      this.pageSize = size
      this.personRecord()
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.personRecord()
    },
    avatar() {
      return getAvatar()
    },
    enableSet() {
      return Number(getUserId()) !== Number(this.userId)
    }
  }
}
</script>

<style scoped>

::v-deep .hide .el-upload--picture-card {
  display: none;
}
.code-hover:hover{
  background-color: #0acf97;
  color: #1C1C1C;
}

.el-divider--horizontal{
  margin: 0;
}

.el-divider--vertical{
  height: 9em;
}

</style>
